package com.seeyon.apps.kkARPEvent.util;

import com.seeyon.ctp.common.AppContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
public class TransHtmlToPdfUtils {
    private static final Log LOGGER = LogFactory.getLog(TransHtmlToPdfUtils.class);

    /**
     * 将html文单转换为PDF文单</br>
     * 需要服务器上安装PDF转换工具，并且在插件配置参数中配置转换工具路径
     * @param htmlFilePath 原始html文件绝对路径
     * @param pdfFilePath 转换后pdf文件绝对路径
     */
    public static boolean transHtmlToPdf(String htmlFilePath, String pdfFilePath) {
        String wkhtmltopdfToolPath = AppContext.getSystemProperty("archivedoc.integration.wkhtmltopdf");
        try {
            if(StringUtils.isNotBlank(wkhtmltopdfToolPath)) {
                File file = new File(htmlFilePath);
                if(!file.exists()) {
                    LOGGER.info("PDF转换源文件不存在：" + htmlFilePath);
                    return false;
                }
                // html 转 pdf 工具 不同操作系统运行不同的命令
                String command = "";
                if(System.getProperty("os.name").startsWith("Windows")) {
                    command = wkhtmltopdfToolPath + " " + htmlFilePath + " " + pdfFilePath;
                } else if(System.getProperty("os.name").startsWith("Linux")) {
                    command = "/usr/local/bin/wkhtmltopdf " + htmlFilePath + " " + pdfFilePath;
                }
                LOGGER.info("PDF转换命令：" + command);
                LOGGER.info("PATH="+System.getenv("PATH"));
                /*Process process = Runtime.getRuntime().exec(command);
                new StreamGobbler(process.getInputStream(), "input").start();
                new StreamGobbler(process.getErrorStream(), "error").start();*/
                int result = execShell(command);
                LOGGER.info("PDF转换结果：" + result);
                if(result == 0) {
                    LOGGER.info("转PDF成功:" + pdfFilePath);
                    return true;
                }
                /*LOGGER.info("PDF转换结果：" + process.waitFor());
                if(process.waitFor() == 0) {
                    LOGGER.info("转PDF成功:" + pdfFilePath);
                    return true;
                }*/
            }
        } catch(Exception e) {
            LOGGER.info("文单转PDF异常:" + e.getMessage());
        }
        return false;
    }
    
    public static int execShell(String shell) {
        StringBuilder result = new StringBuilder();
        Process process = null;
        int waitForCode = 1;
        /*BufferedReader bufferedReaderInfo = null;
        BufferedReader bufferedReaderError = null;
        try {
        	// 执行shell命令，返回了一个进程
            process = Runtime.getRuntime().exec(shell);
            // 等待命令执行完成
            waitForCode = process.waitFor();
            // 获取结果，正常返回是第一个，错误返回是第二个，返回结果只能有一个，要么正常执行，要么执行错误
            bufferedReaderInfo = new BufferedReader(new InputStreamReader(process.getInputStream()));
            bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            // 将返回结果存到一个stringbuilder里面，因为StringBuilder是可扩展的，所以不用String
            while (bufferedReaderInfo.readLine() != null || bufferedReaderError.readLine() != null) {
                if (bufferedReaderInfo.readLine() != null) {
                    line = bufferedReaderInfo.readLine();
                } else {
                    line = bufferedReaderError.readLine();
                }
                result.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 释放资源
            if (bufferedReaderError!=null){
                try {
                    bufferedReaderError.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReaderInfo!=null){
                try {
                    bufferedReaderInfo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process!=null){
                process.destroy();
            }

        }*/      
        try {
        	// 执行shell命令，返回了一个进程
            process = Runtime.getRuntime().exec(shell);
            // 等待命令执行完成
            waitForCode = process.waitFor();
            LOGGER.info("process.waitFor():" + waitForCode);
            // 获取结果，正常返回是第一个，错误返回是第二个，返回结果只能有一个，要么正常执行，要么执行错误
            InputStream inputStream =  process.getInputStream();
            InputStream errorStream =  process.getErrorStream();
            new Thread(() -> {
                String line = "";
                BufferedReader bufferedReaderInfo = null;
                try {
					bufferedReaderInfo = new BufferedReader(new InputStreamReader(inputStream));            	
					while (bufferedReaderInfo.readLine() != null) {
					    if (bufferedReaderInfo.readLine() != null) {
					        line = bufferedReaderInfo.readLine();
					    } 
					    result.append(line + "\n");
					}
				} catch (IOException e) {
					 LOGGER.error("获取正确结果异常:" , e);
				}finally {
		            // 释放资源
		            if (bufferedReaderInfo!=null){
		                try {
		                    bufferedReaderInfo.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		        }
            }).start();
            
            new Thread(() -> {
                String line = "";
                BufferedReader bufferedReaderError = null;
                try {
					bufferedReaderError = new BufferedReader(new InputStreamReader(errorStream));
					// 将返回结果存到一个stringbuilder里面，因为StringBuilder是可扩展的，所以不用String
					while (bufferedReaderError.readLine() != null) {
					    if (bufferedReaderError.readLine() != null) {
					        line = bufferedReaderError.readLine();
					    }
					    result.append(line + "\n");
					}
				} catch (IOException e) {
					LOGGER.error("获取错误结果异常:" , e);
				}finally {
		            // 释放资源
		            if (bufferedReaderError!=null){
		                try {
		                    bufferedReaderError.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		        }
            }).start();            
        } catch (Exception e) {
        	LOGGER.error("执行html转pdf脚本异常:" , e);
        }finally {           
            if (process!=null){
                process.destroy();
            }
        }
        LOGGER.info("执行xshell命令返回result:" + result);
        return waitForCode;
    }
}
